package com.cheung.leetcode.backtrack;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.backtrack
 * @Author :  cheungming
 * @CreateTime : 2024-05-25 09:13:30
 * @Description : 回溯算法
 * @Version : 1.0
 */
public class Code216Test {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(k, n, 1, new ArrayList<>(), res);
        return res;
    }

    public void backtrack(int k, int n, int start, List<Integer> path, List<List<Integer>> res) {
        // 终止条件
        if (path.size() == k) {
            if (path.stream().mapToInt(Integer::intValue).sum() == n) {
                res.add(new ArrayList<>(path));
            }
            return;
        }

        for (int i = start; i <= 9; i++) {
            path.add(i);
            backtrack(k, n, i + 1, path, res);
            // 回溯
            path.remove(path.size() - 1);
        }

    }


    @Test
    public void test1() {
        assert List.of(List.of(1, 2, 4)).equals(combinationSum3(3, 7));
    }

    @Test
    public void test2() {
        assert List.of(List.of(1, 2, 6), List.of(1, 3, 5), List.of(2, 3, 4)).equals(combinationSum3(3, 9));
    }

    @Test
    public void test3() {
        assert List.of().equals(combinationSum3(4, 1));
    }
}
